<template>
  <div class="chat-layout">
    <div class="sidebar">
      <ChatList
        :conversations="conversations"
        :activeId="activeConversationId"
        @select="handleSelectConversation"
        @new="handleNewConversation"
        @rename="handleRename"
        @delete="handleDelete"
      />
    </div>
    <div class="main">
      <Chat
        v-if="chatReady"
        :conversationId="activeConversationId"
        :messages="messages"
        :loading="loading"
        @newConversationCreated="handleNewConversationCreated"
        @refreshConversations="loadConversations"
        @sendMessage="handleSendMessage"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import ChatList from './ChatList.vue'
import Chat from './Chat.vue'
import { getConversations, getMessages, askDify, renameConversation, deleteConversation } from '../api.js'
import { extractConversationId } from '../utils.js'

const conversations = ref([])
const activeConversationId = ref('')
const chatReady = ref(false)
const messages = ref([])
const loading = ref(false)
let sending = false;

async function loadConversations() {
  const res = await getConversations()
  if (res.data && res.data.data && Array.isArray(res.data.data)) {
    conversations.value = res.data.data
  }
  chatReady.value = true
}

async function handleSelectConversation(id) {
  activeConversationId.value = id
  // 拉取历史消息
  const res = await getMessages(id)
  messages.value = (res.data && res.data.data) ? res.data.data : []
}

function handleNewConversation() {
  activeConversationId.value = ''
  messages.value = []
}

function handleNewConversationCreated(newId) {
  loadConversations()
  activeConversationId.value = newId
}

async function handleSendMessage(userInput) {
  if (loading.value || sending) return;
  sending = true;
  messages.value.push({
    id: 'user-' + Date.now(),
    query: userInput
  });
  loading.value = true;
  let answer = '无回复内容';
  let conversationId = activeConversationId.value;
  let isNewConversation = !conversationId;
  try {
    const res = await askDify({ question: userInput, conversationId });
    if (isNewConversation) {
      const newId = extractConversationId(res.data) || (res.data && res.data.conversation_id);
      if (newId) {
        conversationId = newId;
        activeConversationId.value = newId;
        await loadConversations();
        const msgRes = await getMessages(conversationId);
        messages.value = (msgRes.data && msgRes.data.data) ? msgRes.data.data : [];
        loading.value = false;
        sending = false;
        return;
      }
    }
    // 兼容多种返回格式
    if (typeof res.data === 'string' && res.data.includes('data:')) {
      const lines = res.data.split('\n');
      let fullAnswer = '';
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6));
            if (data.event === 'agent_message' && data.answer) {
              fullAnswer += data.answer;
            }
          } catch (e) {}
        }
      }
      answer = fullAnswer || '无回复内容';
    } else if (res.data && res.data.answer) {
      answer = res.data.answer;
    } else if (res.data && res.data.message) {
      answer = res.data.message;
    } else if (res.data && res.data.data && res.data.data.answer) {
      answer = res.data.data.answer;
    }
    messages.value.push({
      id: 'ai-' + Date.now(),
      answer
    });
  } catch (e) {
    answer = `抱歉，请求失败。错误信息: ${e.response?.data?.message || e.message || '未知错误'}`;
    messages.value.push({
      id: 'ai-' + Date.now(),
      answer,
      status: 'error'
    });
  }
  loading.value = false;
  sending = false;
}

async function handleRename(item) {
  const newName = prompt('请输入新的会话名称：', item.name || '')
  if (newName && newName !== item.name) {
    await renameConversation(item.id, newName)
    await loadConversations()
  }
}

async function handleDelete(item) {
  if (confirm('确定要删除该会话吗？')) {
    await deleteConversation(item.id)
    await loadConversations()
    // 如果删除的是当前会话
    if (activeConversationId.value === item.id) {
      if (conversations.value.length > 0) {
        // 切换到第一个会话并拉取历史消息
        activeConversationId.value = conversations.value[0].id
        const res = await getMessages(activeConversationId.value)
        messages.value = (res.data && res.data.data) ? res.data.data : []
      } else {
        // 没有会话了，清空右侧
        activeConversationId.value = ''
        messages.value = []
      }
    }
  }
}

onMounted(() => {
  loadConversations()
})
</script>

<style scoped>
.chat-layout {
  display: flex;
  width: 100%;
  height: 100%;
  min-height: 500px;
  max-height: 800px;
  background: #f5f6fa;
  border-radius: 0 0 18px 18px;
  box-sizing: border-box;
  overflow: hidden;
}
.sidebar {
  width: 30%;
  min-width: 220px;
  max-width: 350px;
  background: #fff;
  border-right: 1px solid #e6e6e6;
  box-shadow: 2px 0 8px #0001;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}
.main {
  width: 70%;
  min-width: 400px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  background: #f5f6fa;
  justify-content: center;
  align-items: center;
}
</style> 